/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/4/30 00:21
 */
package org.mechanic.fund.listener;

import org.mechanic.exception.NoSqlResultException;
import org.mechanic.fund.config.WcBaseInfoProperties;
import org.mechanic.fund.domain.wechat.WcBaseInfo;
import org.mechanic.fund.service.wechat.IWcAccessApiService;
import org.mechanic.fund.service.wechat.IWcBaseInfoService;
import org.mechanic.fund.service.wechat.impl.WcBaseInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.List;

/**
 * 微信上下文监听器
 *
 * @author mechanic
 * @version 0.0.1
 */
//@WebListener
@Component
public class WechatContextListener implements ApplicationListener<ContextRefreshedEvent> {
//public class WechatContextListener implements ServletContextListener {

    private static Logger logger = LoggerFactory.getLogger(WechatContextListener.class);

    private final WcBaseInfoProperties properties;

    private final IWcBaseInfoService baseInfoService;
    private final IWcAccessApiService accessApiService;

    @Autowired
    public WechatContextListener(
      WcBaseInfoProperties properties,
      WcBaseInfoService baseInfoService,
      IWcAccessApiService accessApiService) {
        this.properties = properties;
        this.baseInfoService = baseInfoService;
        this.accessApiService = accessApiService;
    }

    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            this.initWechat();
        }
    }

    private void initWechat() {
        logger.info("开始初始化微信公众平台基础信息......");
        logger.info("开始初始化基础信息...");
        List<WcBaseInfo> baseInfos = this.baseInfoService.getList();
        if (baseInfos == null || baseInfos.size() == 0) {
            String errorMsg = "没有找到微信公众号基础信息，请在wc_base_info表中添加微信公众号基础信息。";
            logger.error(errorMsg);
            throw new NoSqlResultException(errorMsg);
        }

        WcBaseInfo baseInfo = this.baseInfoService.getList().get(0);
        properties.setId(baseInfo.getId());
        properties.setName(baseInfo.getName());
        properties.setMpId(baseInfo.getMpId());
        properties.setSecret(baseInfo.getSecret());
        properties.setType(baseInfo.getType());
        properties.setAppToken(baseInfo.getAppToken());
        properties.setAppEncodingAESKey(baseInfo.getAppEncodingAESKey());
        properties.setIsAuthc(baseInfo.getIsAuthc());
        properties.setQrcode(baseInfo.getQrcode());
        logger.info("基础信息初始化完成。");
        logger.info("获取Token......");
        String token = this.accessApiService.getCropToken(properties.getMpId(), properties.getSecret());
        properties.setCorpToken(token);
        logger.info(MessageFormat.format("企业号[{0}]的Token：{1}", properties.getName(), token));
        logger.info("公众平台基础信息：\n"
                    + "公众号主键编号(ID)：" + properties.getId() + "\n"
                    + "公众号名称(Name)：" + properties.getName() + "\n"
                    + "公众号ID(mpId)：" + properties.getMpId() + "\n"
                    + "公众号密钥(secret)：" + properties.getSecret() + "\n"
                    + "公众号类型。1=订阅号，2=服务号，3=企业号，4=小程序(type)：" + properties.getType() + "\n"
                    + "应用回调的token(appToken)：" + properties.getAppToken() + "\n"
                    + "应用回调的key(appEncodingAESKey)：" + properties.getAppEncodingAESKey() + "\n"
                    + "是否通过微信官方认证(isAuthc)：" + properties.getIsAuthc() + "\n"
                    + "");
        logger.info("微信公众平台基础信息初始化完成。");
        logger.info("============================================================");
        logger.info("系统启动完成。");
        logger.info("============================================================");
    }
}
